package com.develope.tree.image;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.develope.tree.BaseApplication;
import com.develope.tree.Constant;
import com.develope.tree.R;
import com.develope.tree.utils.Utils;


public class ManagerPicture extends Activity {
	

	static final int REQUEST_IMAGE_CAPTURE = 1;
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;


	String mCurrentPhotoPath;
	private ImageSwitcher imageSwitcher;
	LinearLayout myGallery;
	Button bt_takePicture;
	private ImageView mImageView;
	
	private Utils utils;
	private ArrayList<String> imagePaths = new ArrayList<String>();
	private GridView gridView;
	private ImageAdapter adapter;
	private int columnWidth;
	private String user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_take_picture);

		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		// dispatchTakePictureIntent();
		user = extras.getString("user");
		gridView = (GridView) findViewById(R.id.grid_view);
		utils = new Utils(this);
		
		InitilizerGridLayout();
		
		imagePaths = utils.getFilePaths();
		
		adapter = new ImageAdapter(ManagerPicture.this, imagePaths, columnWidth);
		
		gridView.setAdapter(adapter);
		
	}

	
	private void InitilizerGridLayout() {
		// TODO Auto-generated method stub
		Resources r = getResources();
		float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Constant.GRID_PADDING, r.getDisplayMetrics());
		
		int width = r.getDisplayMetrics().widthPixels;
		
		columnWidth = (int) ((width - ((Constant.NUM_OF_COLUMNS+1)*padding))/Constant.NUM_OF_COLUMNS);
		
		gridView.setNumColumns(Constant.NUM_OF_COLUMNS);
		gridView.setColumnWidth(columnWidth);
		gridView.setStretchMode(GridView.NO_STRETCH);
		gridView.setPadding((int) padding, (int) padding, (int) padding, (int) padding);
		gridView.setHorizontalSpacing((int) padding);
		gridView.setVerticalSpacing((int) padding);
		
	}


	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.take_picture, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
//			Bundle data = new Bundle();
//			data.putString("user", user);
//			Intent intent = new Intent(this, CameraActivity.class);
//			intent.putExtras(data);
//			startActivity(intent);
			dispatchTakePictureIntent();
			return true;
		}
		return super.onOptionsItemSelected(item);

	}

		

	private void dispatchTakePictureIntent() {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
			File photoFile = null;
			try {
				photoFile = creatImageFile();
			} catch (IOException ex){
				BaseApplication.makeToastMsg("Cannot Save Photo");
			}
			
			if (photoFile != null){
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
			
			startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setContentView(R.layout.layout_preview);
		mImageView = (ImageView) findViewById(R.id.imgdisplay);
		
		if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK && null !=data) {
			Bundle extras = data.getExtras();
	        Bitmap imageBitmap = (Bitmap) extras.get("data");
	        mImageView.setImageBitmap(imageBitmap);

			
			
		
		}
	}
	
	private void galleryAddPic() {
	    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	    File f = new File(mCurrentPhotoPath);
	    Uri contentUri = Uri.fromFile(f);
	    mediaScanIntent.setData(contentUri);
	    this.sendBroadcast(mediaScanIntent);
	}
	
	private File creatImageFile() throws IOException{
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String imageFileName = "JPEG_"+ timeStamp +"_";
		File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		File image = File.createTempFile(imageFileName, ".jpg", storageDir);
		
		mCurrentPhotoPath = "file:" + image.getAbsolutePath();
		return image;
	}
	
	public static File convertImageUriToFile (Uri imageUri, Activity activity)  {
		Cursor cursor = null;
		try {
		    String [] proj={MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
		    cursor = activity.managedQuery( imageUri,
		            proj, // Which columns to return
		            null,       // WHERE clause; which rows to return (all rows)
		            null,       // WHERE clause selection arguments (none)
		            null); // Order-by clause (ascending by name)
		    int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		    int orientation_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
		    if (cursor.moveToFirst()) {
		        String orientation =  cursor.getString(orientation_ColumnIndex);
		        return new File(cursor.getString(file_ColumnIndex));
		    }
		    return null;
		} finally {
		    if (cursor != null) {
		        cursor.close();
		    }
		}
		}

	
}
